package com.gitee.loyo.spring

import com.zaxxer.hikari.HikariDataSource
import com.gitee.loyo.KSQL
import com.gitee.loyo.jdbc.Conn
import com.gitee.loyo.jdbc.Ds
import com.gitee.loyo.jdbc.JDBC
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Primary
import org.springframework.jdbc.datasource.DataSourceUtils
import org.springframework.transaction.support.TransactionSynchronizationManager
import javax.sql.DataSource


@SpringBootApplication
open class SpringTestApplication {

    companion object {

        @JvmStatic
        fun main(args: Array<String>) {
            runApplication<SpringTestApplication>(*args)
        }
    }

    @Bean
    @Primary
    open fun dataSource(properties: DataSourceProperties): DataSource{
        val dataSource = Ds(properties.initializeDataSourceBuilder().type(HikariDataSource::class.java).build())
        JDBC.init(dataSource)
        KSQL.tryGetConnection = {
            val conn = DataSourceUtils.getConnection(dataSource)?.let {
                Conn.create(it)
            }?.also {
                it.executeOnce = !TransactionSynchronizationManager.isSynchronizationActive()
            }?: throw NullPointerException("未获取Connection")
            conn
        }
        return dataSource
    }
}